//
// Created by hps on 24-4-13.
//

#ifndef JSONCODEHIGHLIGHT_H
#define JSONCODEHIGHLIGHT_H

#include <QtGui/QSyntaxHighlighter>
#include "HeadFiles.h"

namespace hps {


class JsonCodeHighLight: public QSyntaxHighlighter {
public:
    JsonCodeHighLight(QTextDocument *parent = nullptr)
        : QSyntaxHighlighter(parent) {
        setHighLight(parent);;
    }

    void addFormat(QString pattern,
                   Qt::GlobalColor color,
                   bool isBold = false,
                   bool isItailc = false,
                   std::string font = "Ubuntu") {
        QTextCharFormat format;
        if (isBold) {
            format.setFontWeight(QFont::Bold);
        }
        format.setFontItalic(isItailc);
        format.setFontFamily(QString(font.c_str()));
        format.setForeground(color);
        QRegularExpression expression;
        expression.setPattern(pattern);
        m_rules.append({expression, format});
    }

    void setHighLight(QTextDocument *textDocument = nullptr) {
        addFormat(QString("\"(\\w+)\"(\\s)?:"), Qt::blue);
        addFormat(QString("(?<=\":)(.*?)(?=,|\\}|\\]|\\s|[\n\r]|\n)"), Qt::darkGreen);
    }


protected:
    void highlightBlock(const QString &text) override {
        if (text.isEmpty()) {
            return;
        }
        // 对每一行文本应用高亮规则
        for (const HighlightingRule &rule: qAsConst(m_rules)) {
            QRegularExpressionMatchIterator matchIterator = rule.pattern.globalMatch(text);
            while (matchIterator.hasNext()) {
                QRegularExpressionMatch match = matchIterator.next();
                setFormat(match.capturedStart(), match.capturedLength(), rule.format);
            }
        }
    }

private:
    typedef struct _HighlightingRule {
        QRegularExpression pattern;
        QTextCharFormat format;
    } HighlightingRule;

    QVector<HighlightingRule> m_rules;

    QTextCharFormat m_codeBlockFormat;
    QRegularExpression m_commentStartExpression;
    QRegularExpression m_commentEndExpression;
};

} // hps


#endif //JSONCODEHIGHLIGHT_H
